<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/11/22
 * Time: 6:34 PM
 */

namespace app\api\controller;


use Alipay\Alipayobj;
use app\common\controller\ActionLogs;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use Bank\HuifuServer;
use Wechat\Wxobjopen;

class CreateOrder extends Pub
{
    public function create_order($param)
    {

        switch ($param['channel']) {
            case "0":
                $rarr = $this->create_official_order($param, "wechat_way");
                break;
            case "1":
                $rarr = $this->create_official_order($param, "ali_way");
                break;
            case "11":
                $rarr = $this->create_micro_order($param);
                break;
            default:
                $rarr = $this->create_other_order($param);
                break;
        }

        return $rarr;

    }

    private function create_other_order($param)
    {
        $out_trade_no = $this->getorderid($param['merchantid']);
        $data['mid'] = $param['merchantid'];
        $data['orderid'] = $out_trade_no;
        $data['source'] = $param['source'];
        $data['pay_fs'] = $param['channel'];
        $data['d_cashier'] = $param['device_id'];

        $data['kuantai'] = $param['kuantai'];
        $data['price'] = $param['total_fee'];
        $data['yf_price'] = $param['total_fee'];
        $data['pay_cate'] = $param['pay_cate'];
        $data['add_time'] = time();
        $Paylog = new Paylog();
        $add = $Paylog->save($data);
        $infos = ['out_trade_no' => $out_trade_no];
        if ($add) {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['info'] = $infos;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = '订单号获取失败,请尝试重新发起支付';
        }

        return $rarr;
    }

    private function create_official_order($param, $type)
    {
        $Merchant = new Merchant();
        $pay_way = $Merchant->where('id', $param['merchantid'])->value($type);
        $param['pay_way']=$pay_way;
        if ($param['channel'] == 0) {

            switch ($pay_way) {
                case '0':
                    $rarr = $this->create_wx_official_order($param);
                    break;
                case '1':
                    $rarr = $this->create_wx_official_order($param);
                    break;
                case '10':
                    $rarr = "";
                    break;
                case '30':
                    $rarr = $this->create_huifu_wx_order($param);

                    break;
            }

        } elseif ($param['channel'] == 1) {
            switch ($pay_way) {
                case '0':
                    $rarr = $this->create_ali_official_order($param);
                    break;
                case '1':
                    $rarr = $this->create_ali_official_order($param);
                    break;
                case '10':
                    $rarr = "";
                    break;
                case '30':
                    $rarr = $this->create_huifu_ali_order($param);

                    break;
            }
        }
        return $rarr;


    }

    //生成微信官方扫码支付订单
    public function create_wx_official_order($param)
    {
        $ActionLogs = new ActionLogs();
        $ActionLogs->writelog("osapi", "clientlog", "wxpayorder", "client:", $param);
        //END
        $out_trade_no = $this->getorderid($param['merchantid']);;
        $sub_openid = $param['sub_openid'];
        $param['out_trade_no'] = $out_trade_no;
        $this->createpaylog($param);

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();


        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];

        //APP渠道则调用app支付appid   machid
        if (isset($param['source_type'])){
            //app支付
            if ($param['source_type']=="app" && $config['app_appid']){
                $WxAppCreateOrder = new WxAppCreateOrder();
                $res_data = $WxAppCreateOrder->create_wx_official_order($param);
                return $res_data;
            }
            //wxapp支付
            if ($param['source_type']=="wxapp" && $config['wxapp_appid']){
                $WxAppCreateOrder = new WxAppCreateOrder();
//                if ((int)$param['merchantid'] == "1518"){
//                    trace( "create_wx_official_order-1：" . json_encode($param,256),'SysRunErrorLog');
                    $res_data = $WxAppCreateOrder->create_wx_official_order_wxapp($param);
//                }else{
////                    trace( "create_wx_official_order-2：" . json_encode($param,256),'SysRunErrorLog');
//                    $res_data = $WxAppCreateOrder->create_wx_official_order_wxapp_bak($param);
//                }
                return $res_data;
            }
        }
        //END
        $ActionLogs->writelog("osapi", "clientlog", "wxpayorder", "2:", $options);
        $weObj = new Wxobjopen($options);
        $mch_id = $agent['partnerid'];
        $body = "快捷支付";
        $appid = $users['authorizer_appid'];
        $total_fee = $param['total_fee'] * 100;
        $openid = "";
        $notify_url = 'https://api.wunengkeji.com/notify.php/wxofficialnotify';
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
        $nonce_str = $weObj->generateNonceStr();
        $param_data['appid'] = $appid;
        $param_data['sub_appid'] = $sub_appid;
        $param_data['mch_id'] = $mch_id;
        $param_data['sub_mch_id'] = $sub_mch_id;
        $param_data['nonce_str'] = $nonce_str;
        $param_data['body'] = $body;
        $param_data['out_trade_no'] = $out_trade_no;
        $param_data['total_fee'] = $total_fee;
        $param_data['spbill_create_ip'] = $spbill_create_ip;
        $param_data['notify_url'] = $notify_url;
        $param_data['openid'] = $openid;
        $param_data['sub_openid'] = $sub_openid;
        $param_data['attach'] = $param['attach'];
        $param_data['trade_type'] = "JSAPI";
//        trace( "wxpayorder-3:" . json_encode($param_data,256),'SysRunLog');
        $pay_xml = $weObj->createWxPackageXml($param_data);
        $pay_xml = $weObj->get_pay_id($pay_xml);
//        trace( "wxpayorder-4:" . json_encode($pay_xml,256),'SysRunLog');
        if ($pay_xml['return_code'] == "SUCCESS") {
            $prepay_id = $pay_xml['prepay_id'];
            $jsApiObj["appId"] = $appid;
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $nonce_str;
            $jsApiObj["package"] = "prepay_id=" . $prepay_id;
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $out_trade_no;
            $rarr['info'] = $jsApiObj;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $pay_xml['return_msg'];
        }

        return $rarr;
    }

    //生成支付宝官方预支付订单
    public function create_ali_official_order($param)
    {

        $orderid = $this->getorderid($param['merchantid']);
        $param['out_trade_no'] = $orderid;
        $this->createpaylog($param);
        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $param['merchantid']))->find();
        if(!empty($users['ali_merid'])){
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);

        $price = $param['total_fee'];
        $buyer_id = request()->post('sub_openid');
        $body = "快捷支付";
        $total_fee = $price;
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.trade.create";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['notify_url'] = 'https://api.wunengkeji.com/notify.php/aliofficialnotify';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $orderid,
            'total_amount' => $total_fee,
            'subject' => $body,
            'buyer_id' => $buyer_id,
            'alipay_store_id' => $users['ali_store_id'],
//                'store_id'=>I('get.id'),
            'extend_params' => array(
                'sys_service_provider_id' => $agent['sys_service_provider_id'],
            ),

        ));

        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");

        $data['sign'] = $signContent;
        $uid = $aliObj->getuid($data);
        $user = json_decode($uid, true);
        if ($user['alipay_trade_create_response']['code'] == "10000") {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $orderid;
            $rarr['info'] = $user['alipay_trade_create_response']['trade_no'];
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $user['alipay_trade_create_response']['msg'];
        }}else{
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "该商户未开通支付宝支付";
        }
        return $rarr;
    }

    //生成联付通预支付订单
    public function create_lft_order()
    {


    }

    //生成汇付天下预支付订单
    public function create_huifu_wx_order($param)
    {
        $out_trade_no = $this->gethuifuorder($param['merchantid']);
        $param['out_trade_no'] = $out_trade_no;
        $this->createpaylog($param);
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $JsonData['ordAmt'] = number_format($param['total_fee'], 2, ".", "");
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['payChannelType'] = "W1";
        $JsonData['appId'] = $users['authorizer_appid'];
        $JsonData['isRaw'] = "1";
        $JsonData['openId'] = $param['sub_openid'];
//        $JsonData['buyerLogonId']= "";
//        $JsonData['buyerId']= "";
        $JsonData['termOrdId'] = $out_trade_no;
//        $JsonData['outOrdId'] = request()->post('orderid');;
        $JsonData['goodsDesc'] = "快捷支付";
        $JsonData['memberId'] = $config['huifu_memberid'];
        $JsonData['merOperId'] = $config['huifu_meroperid'];
        foreach ($JsonData as $k => $v) {
            $JsonData2[$k] = urlencode($v);
        }
        $JsonData2['merPriv'] = array("merNoticeUrl" => 'https://api.wunengkeji.com/notify.php/huifunotify');
        $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $data['traceNo'] = "H501-" . date('YmdHis') . rand(100, 999);
        $res = $HuifuServer->c2b_pay($data);

        if ($res['respCode'] == "000000") {
            $jsonData = json_decode($res['jsonData'], true);
            $payinfo = json_decode($jsonData['payInfo'], true);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $out_trade_no;
            $rarr['info'] = $payinfo;

        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $res['respDesc'];
        }
        return $rarr;

    }

    public function create_huifu_ali_order($param)
    {
        $out_trade_no = $this->gethuifuorder($param['merchantid']);
        $param['out_trade_no'] = $out_trade_no;
        $this->createpaylog($param);
        $Merchant = new Merchant();
        $Agent = new Agent();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $JsonData['ordAmt'] = number_format($param['total_fee'], 2, ".", "");
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['payChannelType'] = "A1";
        $JsonData['appId'] = $agent['ali_app_id'];
        $JsonData['isRaw'] = "1";
//        $JsonData['buyerLogonId']= "";
        $JsonData['buyerId'] = $param['sub_openid'];
        $JsonData['termOrdId'] = $out_trade_no;
//        $JsonData['outOrdId'] = request()->post('orderid');;
        $JsonData['goodsDesc'] = "快捷支付";
        $JsonData['memberId'] = $config['huifu_memberid'];
        $JsonData['merOperId'] = $config['huifu_meroperid'];
        foreach ($JsonData as $k => $v) {
            $JsonData2[$k] = urlencode($v);
        }
        $JsonData2['merPriv'] = array("merNoticeUrl" => 'https://api.wunengkeji.com/notify.php/huifunotify');
        $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $data['traceNo'] = "WN-" . date('YmdHis') . rand(100, 999);
        $res = $HuifuServer->c2b_pay($data);
        if ($res['respCode'] == "000000") {
            $jsonData = json_decode($res['jsonData'], true);
            $payinfo = json_decode($jsonData['payInfo'], true);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $out_trade_no;
            $rarr['info'] = $payinfo;

        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $res['respDesc'];
        }
        return $rarr;

    }

    private function create_micro_order($param)
    {
        $Merchant = new Merchant();
        $wechat_way = $Merchant->where('id', $param['merchantid'])->value('wechat_way');
        $param['pay_way']=$wechat_way;
        switch ($wechat_way) {
            case '0':
                $rarr = $this->create_wx_micro_order($param);
                break;
            case '2':
                $rarr = $this->create_wx_micro_order($param);
                break;
            case '10':
                $rarr = "";
                break;
            case '30':
                $rarr = $this->create_huifu_micro_order($param);
                break;
        }
        return $rarr;


    }

//生成小程序预支付订单
    public function create_wx_micro_order($param)
    {
        $out_trade_no = $this->getorderid($param['merchantid']);;
        $sub_openid = $param['sub_openid'];
        $param['out_trade_no'] = $out_trade_no;
        $this->createpaylog($param);

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['merchantid'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();

        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);
        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $body = "快捷支付";
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $total_fee = $param['total_fee'] * 100;
        $openid = "";
//            $openid = request()->post('openid');
        $notify_url = 'https://api.wunengkeji.com/notify.php/wxofficialnotify';
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];

        $nonce_str = $weObj->generateNonceStr();
        $param_data['appid'] = $appid;
        $param_data['sub_appid'] = $sub_appid;
        $param_data['mch_id'] = $mch_id;
        $param_data['sub_mch_id'] = $sub_mch_id;
        $param_data['nonce_str'] = $nonce_str;
        $param_data['body'] = $body;
        $param_data['out_trade_no'] = $out_trade_no;
        $param_data['total_fee'] = $total_fee;
        $param_data['spbill_create_ip'] = $spbill_create_ip;
        $param_data['notify_url'] = $notify_url;
        $param_data['openid'] = $openid;
        $param_data['sub_openid'] = $sub_openid;
        $param_data['attach'] = $param['attach'];
        $param_data['trade_type'] = "JSAPI";
        $pay_xml = $weObj->createWxPackageXml($param_data);
        $pay_xml = $weObj->get_pay_id($pay_xml);
        if ($pay_xml['return_code'] == "SUCCESS") {
            $prepay_id = $pay_xml['prepay_id'];
            $jsApiObj["appId"] = $appid;
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $nonce_str;
            $jsApiObj["package"] = "prepay_id=" . $prepay_id;
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '';
            $rarr['out_trade_no'] = $out_trade_no;
            $rarr['info'] = $jsApiObj;
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $pay_xml['return_msg'];
        }

        return $rarr;

    }

    //生成汇付小程序预支付订单
    public function create_huifu_micro_order($param)
    {
        if (isset($param['sub_appid'])) {
            $param['out_trade_no'] = $this->gethuifuorder($param['merchantid']);
            $this->createpaylog($param);

            $Merchant = new Merchant();
            $mchinfo = $Merchant->where('id', $param['merchantid'])->field('huifu_memberid,huifu_meroperid')->find();
            $JsonData['memberId'] = $mchinfo['huifu_memberid'];
            $JsonData['merOperId'] = $mchinfo['huifu_meroperid'];
            $JsonData['ordAmt'] = number_format($param['total_fee'], 2, ".", "");;
            $JsonData['apiVersion'] = "2.0.0.1";
            $JsonData['payChannelType'] = "W2";
            $JsonData['appId'] = $param['sub_appid'];
            $JsonData['isRaw'] = 1;
            $JsonData['openId'] = $param['sub_openid'];
            $JsonData['clientIp'] = $param['client_ip'];
            $JsonData['termOrdId'] = $param['out_trade_no'];
            $JsonData['goodsDesc'] = $param['attach'];
            foreach ($JsonData as $k => $v) {
                $JsonData2[$k] = urlencode($v);
            }
            $JsonData2['merPriv'] = array("merNoticeUrl" => 'https://api.wunengkeji.com/notify.php/huifunotify');
            $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);

            $HuifuServer = new HuifuServer();
            $data['checkValue'] = $HuifuServer->sign($JsonData3);
            $data['jsonData'] = $JsonData3;
//            return $data;
            $res = $HuifuServer->microapp_pay($data);
            if ($res['respCode'] == "000000") {
                $jsonData = json_decode($res['jsonData'], true);
                $payinfo = json_decode($jsonData['payInfo'], true);
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'SUCCESS';
                $rarr['result_msg'] = '';
                $rarr['out_trade_no'] = $param['out_trade_no'];
                $rarr['info'] = $payinfo;

            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = '';
                $rarr['result_code'] = 'FAIL';
                $rarr['result_msg'] = $res['respDesc'];
            }
        } else {
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = "缺少参数sub_appid";
        }
        return $rarr;

    }

    private function createpaylog($param)
    {
        $data['orderid'] = $param['out_trade_no'];
        $data['mid'] = $param['merchantid'];
        $data['openid'] = $param['sub_openid'];
        $data['pay_fs'] = $param['channel'];
        $data['pay_statu'] = 0;
        $data['pay_way'] = $param['pay_way'];
        $data['price'] = $param['total_fee'];
        $data['yf_price'] = $param['total_fee'];
        $data['zk_price'] = 0;
        $data['pay_cate'] = $param['pay_cate'];
        $data['d_cashier'] = $param['device_id'];
        $data['kuantai'] = $param['kuantai'];
        $data['source'] = $param['source'];
        $data['add_time'] = time();
        $data['attach'] = $param['attach'];
        if (isset($param['trade_no'])) {
            $data['trade_no'] = $param['trade_no'];;
        }
        $Paylog = new Paylog();
        $Paylog->save($data);


    }

    public function gethuifuorder($sh)
    {
        $order = "H" . $sh . "f" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }
}